<template>
  <div :id="chartId" style="width:100%;height:100%;" />
</template>

<script>
import * as echarts from 'echarts'
export default {
    name: 'Columnar',
    components: {

    },
    props: {
        chartId: { type: String, default: function() { return 'myCharts' } }, // 图表domid
        chartType: { type: Array, default: function() { return [{ type: 'bar', yAxisIndex: 0, symbol: '' }] } }, // 图表类型，bar:柱状图，line:折线图
        dataZoom: { type: Array, default: function() { return null } }, // x轴数据滚动设置参数,默认不滚动  示例：{type: 'inside',minValueSpan: 5,maxValueSpan: 5}
        top: { type: String, default: function() { return '30' } }, // 图表上边距
        right: { type: String, default: function() { return '1%' } }, // 图表右边距
        bottom: { type: String, default: function() { return '2%' } }, // 图表下边距
        left: { type: String, default: function() { return '1%' } }, // 图表左边距
        title: { type: Object, default: function() { return { name: '', align: 'center', 'size': '15', textStyle: { fontWeight: 400 }} } }, // 统计图标题 对齐方式可设置为left center right 百分比形式
        xData: { type: Array, default: function() { return [] } }, // x轴数据
        xUnit: { type: Object, default: function() { return { name: '', align: 'end', 'size': '12' } } }, // x轴单位 对齐方式可设置为'start''middle' 或者 'center''end' 百分比形式
        yData: { type: Array, default: function() { return [] } }, // y轴数据
        yUnit: { type: Object, default: function() { return { name: '', align: 'end', 'size': '12', lineColor: '#000' } } }, // y轴单位 对齐方式可设置为'start''middle' 或者 'center''end' 百分比形式
        multipleYUnit: { type: Boolean, default: function() { return false } }, // 是否有多个Y轴
        yUnits: { type: Array, default: function() { return [{ name: '', align: 'end', 'size': '12', minInterval: 1 }] } }, // y轴单位 对齐方式可设置为'start''middle' 或者 'center''end' 百分比形式
        // ids: { type: Array, default: function() { return [] } }, // 主键
        color: { type: Array, default: function() { return ['#1E90FF'] } }, // 柱状图颜色
        isTooltip: { type: Boolean, default: function() { return true } }, // 是否显示提示信息
        tooltipType: { type: String, default: function() { return 'none' } }, // 提示信息显示方式 line直线   shadow阴影 cross十字轴准星 none没有样式
        tooltipFormat: { type: String, default: function() { return null } }, // 格式化提示信息 {a}（系列名称），{b}（类目值），{c}（数值）, {d}（无）
        isLegend: { type: Boolean, default: function() { return false } }, // 是否显示图例
        legendAlign: { type: Object, default: null }, // { location:'top bottom left right', align:'20  20%' } 图例位置  默认为auto居中
        legendIcon: { type: String, default: function() { return 'rect' } }, // 'circle'圆点, 'rect'矩形, 'roundRect'圆角矩形, 'triangle'三角形, 'diamond'菱形, 'pin'针型, 'arrow'箭头, 'none' 支持图片链接例如'image://http://xxx.xxx.xxx/a/b.png'
        echartsClick: { type: Function, default: null }, // 柱状图点击事件回调
        xChartNum: { type: Number, default: function() { return 1 } }, // x轴显示图表的个数
        xTypeName: { type: Array, default: null }, // { name: '', icon: '' } x轴系列分类名称   icon 与legendIcon参数相同
        barGap: { type: String, default: function() { return '30%' } }, // 不同系的图表之间间距
        barCategoryGap: { type: String, default: function() { return 0 } }, // 同系之间的图表间距
        barMaxWidth: { type: String, default: function() { return 50 } }, // 每个图表宽度
        markLine: { type: Object, default: function() { return { type: false, name: '平均值', color: '#1E90FF' } } }, // 平均线的名称和颜色
        showData: { type: Object, default: function() { return { isdata: false, align: 'top', color: '#000' } } }, // 是否显示对应数值，颜色设置
        showSplitLine: { type: Boolean, default: function() { return true } }, // 网格分割线
        isStack: { type: Boolean, default: function() { return false } }, // 是否进行图形叠加
        labelFormatter: { type: Function, default: null }, // 格式化图例显示内容
        xLabelInterval: { type: Number, default: function() { return 0 } }, // x轴数据显示规则 隔几个坐标显示一个
        xLabelRotate: { type: Number, default: function() { return 0 } }, // x轴数据旋转角度
        xLabelFormatter: { type: Function, default: null }, // x轴数据格式化
        xytextStyle: { type: Object, default: function() { return { xcolor: '#000', ycolor: '#000' } } }, // 数轴字体颜色
        barWidth: { type: Object, default: function() { return { type: false, width: '' } } }, // 每个柱状图 主子的宽度 type为true 接受自定义 否则默认
        smooth: { type: Boolean, default: function() { return false } }, // 折线图是否曲线显示
        barGradient: { type: Object, default: function() { return { type: false, color: [] } } } // 柱状图渐变色
    },
    data() {
        return {
            myChart: null
        }
    },
    computed: {

    },
    watch: {
        yData(val) {
            this.creatEcharts()
        },
        xData(val) {
            this.creatEcharts()
        }
    },
    created() {
        window.addEventListener('resize', this.onresize)
        this.$bus.on('toggleClick', () => {
            setTimeout(() => {
                this.$nextTick(() => {
                    this.onresize()
                })
            }, 300)
        })
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.onresize)
        this.$bus.off('toggleClick', this.onresize)
    },
    mounted() {
        this.creatEcharts()
        setTimeout(() => {
            this.onresize()
        }, 300)
    },
    methods: {
        creatEcharts() {
            const _this = this
            const vessel = document.querySelector('#' + this.chartId)
            const myChart = echarts.init(vessel)
            this.myChart = myChart
            const newSeries = []
            let yAxisArr = []
            for (let i = 0; i < this.xChartNum; i++) {
                if (this.markLine.type) {
                    const child = {
                        name: this.xTypeName !== null ? this.xTypeName[i].name : '',
                        type: this.chartType[i].type,
                        yAxisIndex: this.chartType[i].yAxisIndex,
                        symbol: this.chartType[i].symbol,
                        stack: this.isStack ? 'one' : null,
                        barMaxWidth: this.barMaxWidth,
                        data: this.yData[i],
                        barGap: this.barGap,
                        barCategoryGap: this.barCategoryGap,
                        markLine: {
                            data: [{
                                name: this.markLine.name,
                                type: 'average',
                                lineStyle: {
                                    color: this.markLine.color
                                }
                            }]
                        },
                        label: {
                            show: this.showData.isdata,
                            position: this.showData.align,
                            color: this.showData.color
                        },
                        smooth: this.smooth
                    }
                    // if (this.xChartNum === 1) {
                    //     child['id'] = ids
                    // }
                    if (typeof this.labelFormatter === 'function') {
                        child.label['formatter'] = this.labelFormatter
                    }
                    if (this.barWidth.type) {
                        child.barWidth = this.barWidth.width
                    }
                    if (this.barGradient.type) {
                        child.itemStyle = {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1, this.barGradient.color
                                )
                            }
                        }
                    }
                    newSeries.push(child)
                } else {
                    const child = {
                        name: this.xTypeName !== null ? this.xTypeName[i].name : '',
                        type: (this.chartType[i] || this.chartType[0]).type,
                        yAxisIndex: (this.chartType[i] || this.chartType[0]).yAxisIndex,
                        stack: this.isStack ? 'one' : null,
                        barMaxWidth: this.barMaxWidth,
                        data: this.yData[i],
                        barGap: this.barGap,
                        barCategoryGap: this.barCategoryGap,
                        label: {
                            show: this.showData.isdata,
                            position: this.showData.align,
                            color: this.showData.color
                        },
                        smooth: this.smooth
                    }

                    // if (this.xChartNum === 1) {
                    //     child['id'] = this.ids
                    // }
                    if (typeof this.labelFormatter === 'function') {
                        child.label['formatter'] = this.labelFormatter
                    }
                    if (this.barWidth.type) {
                        child.barWidth = this.barWidth.width
                    }
                    if (this.barGradient.type) {
                        child.itemStyle = {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1, this.barGradient.color
                                )
                            }
                        }
                    }
                    newSeries.push(child)
                }
            }

            if (this.multipleYUnit) {
                this.yUnits.forEach((item, i) => {
                    const temp = {
                        type: 'value',
                        name: this.yUnits[i].name,
                        nameLocation: this.yUnits[i].align,
                        nameTextStyle: { fontSize: this.yUnits[i].size, align: 'left', lineHeight: this.yUnits[i].lineHeight || 56 },
                        nameGap: this.yUnits[i].nameGap || '10',
                        min: this.yUnits[i].min || 0,
                        max: val => {
                            if (Math.abs(val.max) !== Infinity) {
                                return Number(val.max).toFixed(0)
                            }
                        },
                        minInterval: this.yUnits[i].minInterval || 0,
                        splitNumber: 5,
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: this.yUnits[i].lineColor || '#000'
                            }
                        },
                        axisLabel: {
                            show: true,
                            textStyle: {
                                color: this.xytextStyle.ycolor
                            }
                        },
                        splitLine: {
                            show: this.showSplitLine
                        }
                    }
                    if (typeof this.yUnits[i].labelFormatter === 'function') {
                        temp.axisLabel['formatter'] = this.yUnits[i].labelFormatter
                    }
                    yAxisArr.push(temp)
                })
            } else {
                yAxisArr = [{
                    type: 'value',
                    name: this.yUnit.name,
                    nameLocation: this.yUnit.align,
                    nameTextStyle: { fontSize: this.yUnit.size, align: 'left' },
                    nameGap: this.yUnit.nameGap || '10',
                    min: this.yUnit.min || 0,
                    // minInterval: this.yUnit.minInterval || 0,
                    splitNumber: 5,
                    minInterval: 1,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: this.yUnit.lineColor || '#000'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: this.xytextStyle.ycolor
                        },
                        formatter: this.yUnit.labelFormatter
                    },
                    splitLine: {
                        show: this.showSplitLine
                    }
                }]
            }

            const option = {
                title: {
                    text: this.title.name,
                    left: this.title.align || 'center',
                    size: this.title.size || '15',
                    textStyle: this.title.textStyle
                },
                dataZoom: this.dataZoom,
                color: this.color,
                tooltip: {
                    show: this.isTooltip,
                    trigger: 'axis',
                    axisPointer: {
                        type: this.tooltipType
                    },
                    formatter: this.tooltipFormat
                },
                legend: {
                    show: this.isLegend,
                    data: this.xTypeName,
                    icon: this.legendIcon
                },
                grid: {
                    left: this.left,
                    right: this.right,
                    top: this.top,
                    bottom: this.bottom,
                    containLabel: true
                },
                xAxis: [{
                    name: this.xUnit.name,
                    type: 'category',
                    data: this.xData,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLine: {
                        lineStyle: {
                            color: this.xUnit.lineColor || '#000'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: this.xytextStyle.xcolor
                        },
                        interval: this.xLabelInterval,
                        rotate: this.xLabelRotate, // 旋转角度
                        // formatter: function(value, index) {
                        //     if (_this.xLabelFormatter !== null) {
                        //         const text = _this.xLabelFormatter(value, index)
                        //         return text
                        //     } else {
                        //         return value
                        //     }
                        // }
                        formatter: function(value) {
                            var result = ''
                            var length = value.length
                            var maxLength = 5 // 每行最多显示 5 个字符，根据实际情况调整
                            var rowNumber = Math.ceil(length / maxLength)
                            if (rowNumber > 1) {
                                for (var i = 0; i < rowNumber; i++) {
                                    var startPos = i * maxLength
                                    var endPos = Math.min(startPos + maxLength, length)
                                    var rowData = value.substring(startPos, endPos)
                                    if (i < rowNumber - 1) {
                                        result += rowData + '\n'
                                    } else {
                                        result += rowData
                                    }
                                }
                            } else {
                                result = value
                            }
                            return result
                        }
                    },
                    nameLocation: this.xUnit.align,
                    nameTextStyle: { fontSize: this.xUnit.size }
                }],
                yAxis: yAxisArr,
                series: newSeries
            }
            if (this.legendAlign !== null) {
                const locations = this.legendAlign.location.split(',')
                let aligns = null
                if (typeof this.legendAlign.align === 'string') {
                    aligns = this.legendAlign.align.split(',')
                    for (let i = 0; i < locations.length; i++) {
                        option.legend[locations[i]] = aligns[i] || 0
                    }
                } else {
                    aligns = this.legendAlign.align
                    for (let i = 0; i < locations.length; i++) {
                        option.legend[locations[i]] = aligns
                    }
                }
            }
            myChart.setOption(option, true)
            // 柱状图点击事件
            myChart.off('click')
            myChart.on('click', function(params) {
                if (_this.echartsClick !== null) {
                    _this.echartsClick(params)
                }
            })
        },
        onresize() {
            if (this.myChart !== null) {
                setTimeout(() => {
                    this.myChart.resize()
                }, 100)
            }
        }
    }
}
</script>

<style scoped lang="scss">

</style>
